﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Collections;

namespace DBLibrary
{
    static class DBMapSchemaCache
    {
        private static Dictionary<Type, SchemaCacheItem> mCache = new Dictionary<Type, SchemaCacheItem>();
        public static SchemaCacheItem GetCacheItem(Type t)
        {
            if (!mCache.ContainsKey(t))
            {
                InitCacheItem(t);
            }
            return mCache[t];
        }

        private static void InitCacheItem(Type t)
        {
            SchemaCacheItem item = new SchemaCacheItem();
            item.TableMap = (TableMapAttribute)t.GetCustomAttributes(typeof(TableMapAttribute), false)[0];
            foreach (PropertyInfo info in t.GetProperties())
            {
                object[] cusAtts = info.GetCustomAttributes(typeof(ColumnMapAttribute), true);
                if (cusAtts.Length > 0)
                {
                    ColumnMapAttribute colMap = (ColumnMapAttribute)cusAtts[0];
                    item.SetInfo(info, colMap);
                }
            }
            mCache[t] = item;
        }
    }

    class SchemaCacheItem
    {
        private Dictionary<string, InnerClass> _columnMapDic = new Dictionary<string, InnerClass>(StringComparer.CurrentCultureIgnoreCase);

        public TableMapAttribute TableMap { get; set; }

        public ICollection<string> ColumnNameCollection
        {
            get { return _columnMapDic.Keys; }
        }

        public PropertyInfo GetPropertyInfo(string columnName)
        {
            if (_columnMapDic.ContainsKey(columnName))
            {
                return _columnMapDic[columnName].PropertyInfo;
            }
            return null;
        }

        public ColumnMapAttribute GetColumnMap(string columnName)
        {
            if (_columnMapDic.ContainsKey(columnName))
            {
                return _columnMapDic[columnName].ColumnMap;
            }
            return null;
        }

        public void SetInfo(PropertyInfo info, ColumnMapAttribute columnMap)
        {
            InnerClass ic = new InnerClass { PropertyInfo = info, ColumnMap = columnMap };
            _columnMapDic[columnMap.ColumnName] = ic;
        }

        private class InnerClass
        {
            public PropertyInfo PropertyInfo { get; set; }
            public ColumnMapAttribute ColumnMap { get; set; }
        }
    }
}
